在C#2.0時代以前,是沒有泛型的,所以當我們遇到需求是方法內做相同的事情,但因為輸入或輸出的型別不一樣,我們就必須重複寫出類似的程式
以下的例子是=>不同的輸入型別
但卻做相同的事情 =>印出輸入資料
範例:
最直覺、簡單的做法會寫出三個方法
public class CommonMethod
    {
        /// <summary>
        /// 印出int數值
        /// </summary>
        /// <param name="iParameter"></param>
        public static void ShowInt(int iParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
        }
        /// <summary>
        /// 印出string數值
        /// </summary>
        /// <param name="iParameter"></param>
        public static void ShowString(string iParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
        }
        /// <summary>
        /// 印出DateTime數值
        /// </summary>
        /// <param name="iParameter"></param>
        public static void ShowDateTime(DateTime iParameter)
        {
            Console.WriteLine("This is {0},parameter={1},type={2}",
                typeof(CommonMethod).Name, iParameter.GetType().Name, iParameter);
        }
    }
主程式:
  static void Main(string[] args)
        {
            int iValue = 123;
            string sValue = "123";
            DateTime dtValue = DateTime.Now;
            CommonMethod.ShowInt(iValue);
            CommonMethod.ShowString(sValue);
            CommonMethod.ShowDateTime(dtValue);
        }
執行結果會是:
泛型: 2.0出現的新語法,解決了用一個方法,滿足不同參數型別,做相同的事
它將函式或方法,定義要使用的型別延緩到了,當你開始使用它才定義
泛型的基本結構是在function或class旁邊加上 的符號
<>裡面的 T=> 只是一個名稱,也可以取其他名字如下
範例:
public class GenericMethod 
{
	public static void Show<myName>(myName tParameter) 
	{
		Console.WriteLine("This is {0},parameter={1},type={2}",
		typeof(GenericMethod),tParameter.GetType().Name,tParameter.ToString());
	}
}
主程式:
void Main()
{
	try
	{
		int iValue = 123;
		string sValue = "456";
		DateTime dtValue = DateTime.Now;
		GenericMethod.Show<int>(iValue);
		GenericMethod.Show<string>(sValue);
		GenericMethod.Show<DateTime>(dtValue);
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}
}
重點提醒
關於泛型的好處與原理、泛型約束、泛型快取、協變、逆變之後會專門寫一篇文章跟大家講解
本篇已同步發表至個人部落格
https://moushih.com/2022ithome07/